package fr.lelouet.monitoring.snapshot;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * snapshot of the usages of a VM resources.<br />
 * */
public class VMSnapshot extends HashMap<String, Float> implements Serializable {

	private static final Logger logger = LoggerFactory
			.getLogger(VMSnapshot.class);

	private static final long serialVersionUID = 1L;

	/** time the last data were imported at */
	public long lastUpdate = 0;

	/** last snapshot duration for data */
	public long lastDuration = 0;

	protected String id;

	public String getId() {
		return id;
	}

	public VMSnapshot(String id) {
		this.id = id;
	}

	/** select the events in the map and modify them */
	public void update(Map<String, String> map) {
		try {
			if (map.containsKey("time")) {
				long time = Long.parseLong(map.get("time"));
				if (time < lastUpdate) {
					return;
				} else {
					lastUpdate = time;
				}
			} else {
				lastUpdate = System.currentTimeMillis();
			}
			for (String mkey : map.keySet()) {
				if (UnusedEntries.contains(mkey)) {
					continue;
				}
				String mval = map.get(mkey);
				try {
					float val = Float.parseFloat(mval);
					put(mkey, val);
				} catch (ClassCastException e) {
					System.out.println("skipping val " + mval + ": "
							+ mval.getClass() + " : " + e.toString());
				}
			}

		} catch (Exception e) {
			logger.error(e.toString());
			return;
		}
	}

	public static final Set<String> UnusedEntries = Collections
			.unmodifiableSet(new HashSet<String>(Arrays.asList(new String[] {
					"time", "seconds", "pid",
					fr.lelouet.monitoring.perf.Tools.HVIdKEY })));

	@Override
	public VMSnapshot clone() {
		VMSnapshot ret = new VMSnapshot(id);
		for (String key : keySet()) {
			ret.put(key, get(key));
		}
		ret.lastDuration = lastDuration;
		ret.lastUpdate = lastUpdate;
		return ret;
	}
}
